﻿using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.SystemFramework.Models;
using System.Text;
using System.Extensions;


namespace System.SystemFramework
{
    public class ConfigManager
    {
        private static IConfigurationRoot Configruation => new ConfigurationBuilder()
                        .SetBasePath(Directory.GetCurrentDirectory())
                        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                        .AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true)
                        .AddJsonFile("appsettings.production.json", optional: true, reloadOnChange: true)
                        .Build();

        public ConnectionOptions this[string key]
        {
            get
            {
                try
                {
                    ConnectionOptions Options = new ConnectionOptions();
                    if (HttpContext.Current == null)
                    {
                        Configruation.GetSection(key).Bind(Options);
                        return Options;
                    }

                    var ObjectOptions = HttpContext.Current.Items[SystemEnums.AppSetting.ConnectionStrings];
                    if (ObjectOptions == null)
                    {
                        Configruation.GetSection(key).Bind(Options);
                        HttpContext.Current.Items[SystemEnums.AppSetting.ConnectionStrings] = Options;
                        return Options;
                    }
                    return (ConnectionOptions)ObjectOptions;
                }
                catch (Exception) { }
                return null;
            }

        }


        /// <summary>
        /// 获取该节点对对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T GetModel<T>(string key) where T : class, new()
        {
            return Configruation.GetSection(key).Get<T>();
        }
    }
}